package com.zhongyouyun.wx.wxapplet.jyj.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.config.RedisConfig;
import com.zhongyouyun.config.WxMaConfig;
import com.zhongyouyun.jyj.model.SspWxUserModel;
import com.zhongyouyun.jyj.service.SspWxUserService;
import com.zhongyouyun.other.model.Result;
import com.zhongyouyun.other.model.TokenUtil;
import com.zhongyouyun.utils.ModelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: shenyi
 * @Date: 2023-08-01
 * @Description:
 */
@RestController
@RequestMapping("wx/wxapplet/jyj/wxUser")
@Api(value = "教育局-微信小程序登录操作", tags = {"教育局-微信小程序登录操作"})
public class WxAppletSspUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SspWxUserService wxUserService;
    @Resource
    private RedisConfig redisConfig;

    @GetMapping("/Login")
    @ApiOperation(value = "微信小程序获取openid", notes = "微信小程序获取openid")
    public Result Login(@ApiParam(name = "微信用户标识code", value = "code", required = true) @RequestParam(value = "code") String code, HttpServletRequest request) {
        WxMaService wxService = WxMaConfig.getMaService("wx53120b685eb1d78d");
        try {
            if (ObjectUtil.isNotEmpty(wxService)) {
                WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
                this.logger.info(session.getOpenid());
                //TODO 可以增加自己的逻辑，关联业务相关数据
                QueryWrapper<SspWxUserModel> queryWrapper = new QueryWrapper<SspWxUserModel>();
                queryWrapper.eq("open_id",session.getOpenid());
                List<SspWxUserModel> wxUserModels = wxUserService.selectList(queryWrapper);
                if(wxUserModels.size() == 1){
                    SspWxUserModel user = wxUserModels.get(0);
                    Subject subject = SecurityUtils.getSubject();
                    UsernamePasswordToken token = new UsernamePasswordToken(request.getHeader("type")+"_" + user.getId().toString(), "123456", true);
                    subject = SecurityUtils.getSubject();
                    subject.login(token);
                    String u_token = TokenUtil.getToken(user.getOpenId() + "_" + user.getId(), subject.getSession().getId().toString(), token.getHost());
                    redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
                    redisConfig.set(u_token, user, 60 * 60 * 60 * 2L);
                    Map map = new HashMap();
                    map.put("WxOpenid",session.getOpenid());
                    map.put("WxUnionid",session.getUnionid());
                    map.put("token",u_token);
                    map.put("userInfo",user);
                    return Result.builder().message("成功").status(0).data(map).build();
                }else if(wxUserModels.size() == 0){
                    SspWxUserModel user = new SspWxUserModel();
                    user.setOpenId(session.getOpenid());
                    user.setUnionId(session.getUnionid());
                    ModelUtils modelutils = new ModelUtils();
                    modelutils.initModel(user, "510");
                    wxUserService.saveOrUpdate(user);
                    Subject subject = SecurityUtils.getSubject();
                    UsernamePasswordToken token = new UsernamePasswordToken(request.getHeader("type")+"_" + user.getId().toString(), "123456", true);
                    subject = SecurityUtils.getSubject();
                    subject.login(token);
                    String u_token = TokenUtil.getToken(user.getOpenId() + "_" + user.getId(), subject.getSession().getId().toString(), token.getHost());
                    redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
                    redisConfig.set(u_token, user, 60 * 60 * 60 * 2L);
                    Map map = new HashMap();
                    map.put("WxOpenid",session.getOpenid());
                    map.put("WxUnionid",session.getUnionid());
                    map.put("token",u_token);
                    map.put("userInfo",user);
                    return Result.builder().message("成功").status(0).data(map).build();
                }else{
                    return Result.builder().message("获取失败").success(false).status(1).build();
                }
            }
            return Result.builder().message("获取失败").success(false).status(1).build();
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return Result.builder().message("获取失败").success(false).status(1).build();
        }
    }
}
